<template>
  <a-modal
    v-model:visible="visible"
    title="添加您的审核结果"
    :width="650"
    :mask-closable="false"
    @cancel="handleCancel"
  >
    <a-spin :spinning="loading">
      <a-form
        ref="FormRef"
        :model="formFields"
        :rules="formRules"
        :label-col="{ style: { width: '80px' } }"
        :wrapper-col="{ span: 14 }"
        autocomplete="off"
      >
        <a-form-item label="审核结果" name="approveStatus">
          <a-radio-group v-model:value="formFields.approveStatus" name="radioGroup" @change="handleChange">
            <a-radio :value="SUCCESS">通过</a-radio>
            <a-radio :value="FAIL">不通过</a-radio>
            <a-radio :value="FOUR">修改建议</a-radio>
          </a-radio-group>
        </a-form-item>
        <!-- <a-form-item v-if="formFields.productId === 7 && agree" label="移动端审核" name="wapApproveStatus">
          <a-radio-group v-model:value="formFields.wapApproveStatus" name="radioGroup" @change="handleChange">
            <a-radio :value="SUCCESS">通过</a-radio>
            <a-radio :value="FAIL">不通过</a-radio>
          </a-radio-group>
        </a-form-item> -->
        <a-form-item label="选择行业" name="industryCode" v-if="agree">
          <industry-cascader
            v-model:industry-id="formFields.industryId"
            :industry-list="industryList"
            @change="handleIndustryChange"
          />
        </a-form-item>
        <!--  -->
        <template v-if="[2, 6, 7, 9, 10, 12, 13].includes(formFields.productId) && agree">
          <a-form-item label="提单价" name="marketPrice">
            <a-input v-model:value="formFields.marketPrice" placeholder="请输入提单价" />
          </a-form-item>

          <a-form-item label="市场价" name="comboPrice">
            <a-input v-model:value="formFields.comboPrice" placeholder="请输入市场价" />
          </a-form-item>
        </template>
        <!-- -->
        <ybs v-if="agree" :category="formFields.productId">
          <template #cibao>
            <!-- <a-form-item label="提单价" name="comboPrice">
              <a-input v-model:value.number="formFields.comboPrice" placeholder="请输入提单价" />
            </a-form-item> -->
          </template>
          <template #hjbw>
            <a-form-item label="提单价" name="comboPrice">
              <a-input-number
                style="width: 100%"
                v-model:value.number="formFields.comboPrice"
                placeholder="请输入提单价"
                :min="0"
              />
            </a-form-item>
          </template>
          <template #bw>
            <a-form-item label="系统报价" name="originalAssessmentPrice">
              <div class="box">
                <a-input readonly :value="formFields.originalAssessmentPrice" placeholder="请输入系统报价" />
                <span class="tip">含图片</span>
              </div>
            </a-form-item>
            <a-form-item label="提单价" name="assessmentPrice">
              <div class="box">
                <a-input
                  v-model:value.number="formFields.assessmentPrice"
                  placeholder="请输入提单价"
                  @change="handleAssessmentPrice"
                />
                <span class="tip">含图片</span>
              </div>
            </a-form-item>
            <a-form-item label="市场价" name="marketPrice">
              <div class="box">
                <a-input readonly v-model:value="formFields.marketPrice" placeholder="请输入市场价" />
                <span class="tip">含图片+溢价</span>
              </div>
            </a-form-item>
          </template>
        </ybs>
        <div class="yaoxi" v-if="getRenewDasius && agree">
          {{ getRenewDasius }}
        </div>
        <a-form-item label="审核意见" name="approveInfo" v-if="!agree">
          <a-textarea
            v-model:value="formFields.approveInfo"
            placeholder="请输入审核意见"
            :auto-size="{ minRows: 3, maxRows: 5 }"
            @input="handleApproveInfo"
          />
        </a-form-item>
        <!-- <a-form-item label="特批" name="tpCode" v-if="agree">
          <a-radio-group v-model:value="formFields.tpCode" name="radioGroup">
            <a-radio :value="1">特批</a-radio>
            <a-radio :value="2">常规</a-radio>
          </a-radio-group>
        </a-form-item>
         -->
        <div style="display: flex">
          <div style="width: 280px">
            <a-form-item label="特批" name="tpCode" v-if="agree">
              <a-radio-group v-model:value="formFields.tpCode" name="radioGroup">
                <a-radio :value="1">特批</a-radio>
                <a-radio :value="2">常规</a-radio>
              </a-radio-group>
            </a-form-item>
          </div>
          <div><a-button v-if="agree" type="primary" @click="dianchakedu">查看额度</a-button></div>
        </div>
        <a-form-item label="类型" name="tpType" v-if="agree && formFields.tpCode == 1">
          <multiplechoice
            ref="multipleChoiceRef"
            v-model:industry-id="formFields.tpType"
            :industry-list="TPOptions"
            @change="handleTpTypeChange"
          />
        </a-form-item>
        <!--  -->
        <a-form-item label="优惠金额" name="tpAmount" v-if="formFields.tpCode == 1">
          <a-input-number
            style="width: 100%"
            v-model:value="formFields.tpAmount"
            :min="1"
            :formatter="(value) => `${value}`.replace(/\D/g, '')"
            :parser="(value) => value.replace(/\D/g, '')"
            placeholder="请输入正整数金额"
          />
        </a-form-item>
        <a-form-item label="备注" name="tpNotes" v-if="agree && formFields.tpCode == 1">
          <a-textarea
            v-model:value="formFields.tpNotes"
            placeholder="请输入特批备注"
            :auto-size="{ minRows: 3, maxRows: 5 }"
          />
        </a-form-item>
        <a-form-item v-if="prompt" :wrapperCol="{ span: 18, offset: 3 }">
          <p class="prompt"><ExclamationCircleOutlined /> {{ prompt }}</p>
        </a-form-item>
      </a-form>
    </a-spin>

    <template #footer>
      <a-button :disabled="loading" key="submit" type="primary" :loading="submitting" @click="handleSubmit">
        提交
      </a-button>
      <a-button key="back" @click="handleCancel"> 取消 </a-button>
    </template>
  </a-modal>

  <div>
    <a-modal v-model:visible="openchakndhsneud" :title="`当前大区：` + disoxd" :width="1000" @ok="handleOkchakndhsneud">
      <a-table :columns="columns" :data-source="diaodata">
        <template #headerCell="{ column }">
          <template v-if="column.key === 'name'">
            <span>
              <smile-outlined />
              Name
            </span>
          </template>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'name'">
            <a>
              {{ record.name }}
            </a>
          </template>
          <template v-else-if="column.key === 'tags'">
            <span>
              <a-tag
                v-for="tag in record.tags"
                :key="tag"
                :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
              >
                {{ tag.toUpperCase() }}
              </a-tag>
            </span>
          </template>
          <!-- <template v-else-if="column.key === 'action'">
            <span>
              <a>Invite 一 {{ record.name }}</a>
              <a-divider type="vertical" />
              <a>Delete</a>
              <a-divider type="vertical" />
              <a class="ant-dropdown-link">
                More actions
                <down-outlined />
              </a>
            </span>
          </template> -->
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script setup lang="ts" name="AuditResultUpdater">
import { computed, onMounted, ref } from 'vue'
import { useVModel } from '@vueuse/core'
import { message, type FormInstance, type RadioChangeEvent } from 'ant-design-vue'
import type { AuditResult } from '@/services/price-sheet/getAuditResult'
import IndustryCascader from '@/components/industry-cascader/index.vue'
import multiplechoice from '@/components/multiplechoice/index.vue'
import Ybs from '@/components/ybs/index.vue'
import { useCategory } from '@/hooks/useCategotry'
import { Rule } from 'ant-design-vue/lib/form'
import type { Industry } from '@/core/interfaces/industry'
import { ApproveStatusEnum } from '@/core/enums/status'
import { ProductEnum } from '@/core/enums/platform'
import { IsFromHjzwEnum } from '@/core/enums/type'
import HJBWFooter from './HJBWFooter.vue'
import getTpTypeList from '@/services/price-sheet/getTpTypeList'
import getSpecialApprove from '@/services/price-sheet/getSpecialApprove'
import { IsTPEnum } from '@/core/enums/type'
import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
function change(val: any) {
  console.log(val)
}
function handleKeyDown(e: any) {
  const key = e.key || e.code
  if (key === '.' || key === 'NumpadDecimal') {
    e.preventDefault()
  }
}

interface Props {
  show: boolean
  data: Partial<AuditResult>
  industryList: Industry[]
  submitting: boolean
  loading: boolean
  industryCode?: number
  prompt?: string
  getRenewDasius?: string
  proxyIds?: number
}
//
interface Emits {
  (e: 'on-submit'): void
  (e: 'on-industry-change'): void
  (e: 'on-price-input', v: any): void
  (e: 'on-tp-type-change', ways: string): void // 添加这个事件
}
const handleTpTypeChange = (data) => {
  console.log(data.ways, '选中的值')
  emit('on-tp-type-change', data.ways) // 触发事件并传递 data.way
}
const props = withDefaults(defineProps<Props>(), {
  show: false,
  submitting: false,
  loading: false,
  industryList: () => [],
  proxyIds: undefined
})

const emit = defineEmits<Emits>()

const visible = useVModel(props, 'show')
const formFields = useVModel(props, 'data')
const FormRef = ref<FormInstance>()
const { BW, BWYXB, CiBao, CBYXB, HJBW } = useCategory(formFields.value.productId)
const { SUCCESS, FAIL, FOUR } = ApproveStatusEnum
const approveInfo = ref('')
const agree = computed(() => {
  return formFields.value.approveStatus === SUCCESS
})

const isTp = computed(() => {
  return formFields.value.tpCode === IsTPEnum.Yes
})

// 点击查看额度
const columns = [
  {
    title: '归属大区',
    dataIndex: 'organize',
    key: 'organize'
  },
  {
    // name: '上月业绩',
    title: '上月业绩',
    dataIndex: 'lastMonthYeJi',
    key: 'lastMonthYeJi'
  },
  {
    title: '总金额额度',
    dataIndex: 'sumAmount',
    key: 'sumAmount'
  },
  {
    title: '已使用金额额度',
    key: 'usedAmount',
    dataIndex: 'usedAmount'
  },
  {
    title: '剩余金额额度',
    key: 'remainAmount',
    dataIndex: 'remainAmount'
  },

  {
    title: '总个数额度',
    key: 'sumNumber',
    dataIndex: 'sumNumber'
  },
  {
    title: '已使用个数额度',
    key: 'usedNumber',
    dataIndex: 'usedNumber'
  },
  {
    title: '剩余个数额度',
    key: 'remainNumber',
    dataIndex: 'remainNumber'
  },
  {
    title: '超额度扣业绩金额',
    key: 'exceedLimitAmount',
    dataIndex: 'exceedLimitAmount'
  }

  // {
  //   title: 'Action',
  //   key: 'action'
  // }
]
const openchakndhsneud = ref(false)
const handleOkchakndhsneud = (e) => {
  console.log(e)
  openchakndhsneud.value = false
}
const diaodata = ref([])
const disoxd = ref('')
const dianchakedu = async () => {
  // console.log('查看额度', props.proxyIds)

  // if (!props.proxyIds) {
  //   message.error('缺少必要的参数')
  //   return
  // }

  openchakndhsneud.value = true
  try {
    const response = await fetch(`http://c.e-baixing.com:7089/api/v3/getTpKanBan?proxyId=${props.proxyIds}`)
    const data = await response.json()
    console.log('查看额度数据:', data)
    diaodata.value = data.list
    disoxd.value = data.organize
  } catch (error) {
    console.error('调用接口出错:', error)
    message.error('获取额度信息失败')
  }
}

const tpAmountIsShow = computed(() => {
  return formFields.value.tpType?.includes('价格优惠申请')
})
// 在父组件中
const multipleChoiceRef = ref()

// 判断是否选择了"扣业绩"
const hasDeductionPerformance = computed(() => {
  return multipleChoiceRef.value?.selectedItems?.some((item) => item.label === '扣业绩') || false
})
const formRules = computed(() => {
  return {
    approveStatus: [
      {
        required: true,
        trigger: 'change',
        message: '请选择审核结果'
      }
    ],

    wapApproveStatus: [
      {
        required: true,
        trigger: 'blur',
        message: '请选择审核结果'
      }
    ],
    industryCode: [
      {
        required: agree.value,
        trigger: 'blur',
        message: '请选择行业'
      }
    ],
    assessmentPrice: [
      {
        required: (BW.value || BWYXB.value) && agree.value,
        trigger: 'blur',
        validator: checkAssessmentPrice
      }
    ],
    marketPrice: [
      {
        required:
          formFields.value.productId && [2, 6, 7, 9, 10, 12, 13].includes(formFields.value.productId) && agree.value,
        trigger: 'blur',
        message: '请输入提单价'
      }
    ],
    originalAssessmentPrice: [
      {
        required: (BW.value || BWYXB.value) && agree.value,
        trigger: 'blur',
        message: '请输入原价'
      }
    ],
    comboPrice: [
      {
        required: (CiBao.value || CBYXB.value) && agree.value,
        trigger: 'blur',
        validator: checkComboPrice
      },
      {
        required: HJBW.value && agree.value,
        trigger: 'blur',
        message: '请输入提单价'
      },
      {
        required:
          formFields.value.productId && [2, 6, 7, 9, 10, 12, 13].includes(formFields.value.productId) && agree.value,
        trigger: 'blur',
        message: '请输入市场价'
      }
    ],
    approveInfo: [
      {
        required: true,
        trigger: 'blur',
        message: '请输入审核意见'
      }
    ],
    tpType: [
      {
        required: isTp.value,
        trigger: 'blur',
        message: '请选择类型'
      }
    ],
    tpAmount: [
      {
        required: hasDeductionPerformance.value, // 仅当选择了"扣业绩"时必填
        trigger: ['blur', 'change'],
        message: '请输入优惠金额（必须为正整数）',
        validator: (_, value) => {
          if (hasDeductionPerformance.value) {
            if (!value) return Promise.reject('请输入优惠金额')
            if (Number(value) <= 0) return Promise.reject('金额必须大于0')
          }
          return Promise.resolve()
        }
      }
    ]
  }
})

function checkAssessmentPrice(_: Rule, value: string) {
  if ((BW.value || BWYXB.value) && agree.value) {
    if (!value) {
      return Promise.reject('请输入提单价')
    }

    if (Number(value) > 0) {
      return Promise.resolve()
    } else {
      return Promise.reject('提单价必须大于0')
    }
  } else {
    return Promise.resolve()
  }
}

function checkComboPrice(_: Rule, value: string) {
  if ((CiBao.value || CBYXB.value) && agree.value) {
    if (!value) {
      return Promise.reject('请输入提单价')
    }

    if (Number(value) > 0) {
      return Promise.resolve()
    } else {
      return Promise.reject('提单价必须大于0')
    }
  } else {
    return Promise.resolve()
  }
}

function handleIndustryChange() {
  formFields.value.industryCode = props.industryList.find((item) => item.id === formFields.value.industryId)?.code

  // 词包不需要调用接口获取提单价
  if (BW.value || BWYXB.value) {
    emit('on-industry-change')
  }
}

function handleApproveInfo() {
  approveInfo.value = formFields.value.approveInfo || ''
}

function handleChange(e: RadioChangeEvent) {
  const val = e.target.value as ApproveStatusEnum

  if (val === SUCCESS) {
    formFields.value.approveInfo = ''
  } else {
    formFields.value.approveInfo = approveInfo.value
  }
}

function handleAssessmentPrice(e: InputEvent) {
  emit('on-price-input', e)
}

function handleSubmit() {
  FormRef.value?.validate().then(() => {
    emit('on-submit')
  })
}

function handleCancel() {
  FormRef.value?.resetFields()
  visible.value = false
}

const TPOptions = ref<{ label?: string; value?: string }[]>()
const [, getTpTypeListFn, TPloading] = getTpTypeList()

const [, getSpecialApproveFn] = getSpecialApprove()

async function getTypeList() {
  // const [err, res] = await getTpTypeListFn()
  const [err, res] = await getSpecialApproveFn()

  console.log(res.data.data, '审核接口类型111')

  if (!err) {
    TPOptions.value = convertToTargetFormat(res.data.data)
    console.log(TPOptions.value, '审核接口类型222')
  } else {
    message.error(err.message || '获取类型列表失败！')
  }
}

function convertToTargetFormat(data) {
  return data.map((item) => {
    const newItem = {
      id: item.id,
      value: item.name,
      label: item.name,
      way: item.way
    }

    if (item.children && item.children.length > 0) {
      newItem.children = convertToTargetFormat(item.children)
    } else {
      newItem.children = [] // 如果没有子节点，也保留children属性
    }

    return newItem
  })
}
onMounted(() => {
  getTypeList()
})
</script>

<style scoped>
.prompt {
  color: red;
  font-size: 13px;
}

.box {
  display: flex;
}

.tip {
  width: 100px;
  font-size: 12px;
  color: #999;
  margin-left: 5px;
}

.yaoxi {
  margin-left: 32px;
  margin-bottom: 10px;
}
</style>
